<?php


namespace Bxy\Jwt\middleware;

use Bxy\Jwt\exception\TokenExpiredException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class JWTAuthAndRefresh  extends BaseMiddleware implements MiddlewareInterface
{
    /**
     * @inheritDoc
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // TODO: Implement process() method.
        try {
            $this->auth->auth();
        } catch (TokenExpiredException $e) {
            $this->auth->setRefresh();
            $response = $handler->handle($request);

            return $this->setAuthentication($response);
        }
        return  $handler->handle($request);
    }
}
